import {ApiClient} from './api'
import {createSilentConfig} from '@/utils/responseHandler'
import {getCurrentDateTime} from '@/utils/date'

export interface Statistics {
  products: number
  schemas: number
  tables: number
  columns: number
  constraints: number
  indexes: number
  dictionaries: number
  fieldLibraries: number
  lastUpdate: string
}

export interface StatisticsItem {
  key: string
  count: number
  lastUpdate: string
}

/**
 * 统计数据API服务
 */
export const statsService = {
  // 获取系统统计数据 - 一次性获取所有统计信息
  async getSystemStats() {
    return ApiClient.get<Statistics>('/statistics', createSilentConfig())
  },

  // 获取产品统计
  async getProductStats() {
    return ApiClient.get<StatisticsItem>('/statistics/products', createSilentConfig())
  },

  // 获取Schema统计
  async getSchemaStats() {
    return ApiClient.get<StatisticsItem>('/statistics/schemas', createSilentConfig())
  },

  // 获取数据表统计
  async getTableStats() {
    return ApiClient.get<StatisticsItem>('/statistics/tables', createSilentConfig())
  },

  // 获取字段统计
  async getColumnStats() {
    return ApiClient.get<StatisticsItem>('/statistics/columns', createSilentConfig())
  },

  // 获取约束统计
  async getConstraintStats() {
    return ApiClient.get<StatisticsItem>('/statistics/constraints', createSilentConfig())
  },

  // 获取索引统计
  async getIndexStats() {
    return ApiClient.get<StatisticsItem>('/statistics/indexes', createSilentConfig())
  },

  // 获取数据字典统计
  async getDictionaryStats() {
    return ApiClient.get<StatisticsItem>('/statistics/dictionaries', createSilentConfig())
  },

  // 获取字段库统计
  async getFieldLibraryStats() {
    return ApiClient.get<StatisticsItem>('/statistics/field-libraries', createSilentConfig())
  },

  // 批量获取所有统计数据
  async getAllStats() {
    const requests = [
      this.getProductStats(),
      this.getSchemaStats(),
      this.getTableStats(),
      this.getColumnStats(),
      this.getConstraintStats(),
      this.getIndexStats(),
      this.getDictionaryStats(),
      this.getFieldLibraryStats()
    ]

    const results = await Promise.allSettled(requests)

    const stats: Partial<Statistics> = {}
    const statsMap: Record<string, StatisticsItem> = {}

    results.forEach((result, index) => {
      if (result.status === 'fulfilled' && result.value.success && result.value.data) {
        const key = getStatKey(index)
        statsMap[key] = result.value.data
        if (key !== 'lastUpdate') {
          stats[key as keyof Omit<Statistics, 'lastUpdate'>] = result.value.data.count
        }
      }
    })

    // 添加最后更新时间
    const timestamps = Object.values(statsMap).map(item => item.lastUpdate).filter(Boolean)
    stats.lastUpdate = timestamps.length > 0 ? getCurrentDateTime() : getCurrentDateTime()

    return {
      success: true,
      data: stats as Statistics,
      status: 200,
      headers: {}
    }
  }
}

/**
 * 根据索引获取统计项键名
 */
function getStatKey(index: number): string {
  const keys = [
    'products', 'schemas', 'tables', 'columns',
    'constraints', 'indexes', 'dictionaries', 'fieldLibraries'
  ]
  return keys[index] || 'unknown'
}

/**
 * 统计数据API服务（兼容旧版本）
 */
export const legacyStatsService = {
  // 获取系统统计数据 - 一次性获取所有统计信息
  getSystemStats() {
    return ApiClient.get<Statistics>('/statistics', createSilentConfig()).then(result => {
      if (result.success) {
        return Promise.resolve({ data: result.data })
      } else {
        return Promise.reject(result.error)
      }
    })
  }
}

export default statsService